package net.xinqushi.socket.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author xjie 2019/7/17 14:57
 * @description 非阻塞client
 */
public class NonBlockClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);//non-Blocking
        socketChannel.connect(new InetSocketAddress("localhost", 5555));
        //如果SocketChannel在非阻塞模式下，此时调用connect()，该方法可能在连接建立之前就返回了。
        //为了确定连接是否建立，可以调用finishConnect()的方法。像这样：
        while(socketChannel.finishConnect() ){
            ByteBuffer buf = ByteBuffer.allocate(48);
            String newData = "New String to write to file..." + System.currentTimeMillis();
            buf.put(newData.getBytes());
            buf.flip();//ready for read
            while(buf.hasRemaining()) {
                //非阻塞模式下，write()方法在尚未写出任何内容时可能就返回了。所以需要在循环中调用write()
                socketChannel.write(buf);
            }
            break;
        }
        socketChannel.close();

    }
}
